<?php
class ss_api_jsonQuery extends ss_konstrukt_component{
	protected function map($name){
		$_interfaces=SITE_ROOT_PATH.'/htdocs/api/interface.data';
		if(!file_exists($_interfaces)) throw new k_PageNotFound();
		//ss_error::log($this->interfaces,'Interfaces');
		ss_error::log($name,'Mapping');
		if($name==$this->settings['server']['api']['interface']){
			return 'ss_api_interface';
		}
		ss_doctrine_table::$RELATION_MODE=1;
		ss_doctrine_table::$LIMIT=0;
		ss_doctrine_query::$LIMIT=0;
		define('SS_BASE_LANG',$this->settings['i18n']['default']);
		if(array_key_exists($name,$_keys=unserialize(file_get_contents($_interfaces)))) return 'ss_api_jsonQuery_master';
		//ss_error::log($_keys,$name);
		if(class_exists($_class='site_api_'.$name)) return $_class;
	}
}

class ss_api_jsonQuery_master extends ss_konstrukt_masterComponent{
	public $mapper;
	public $data=array();
	protected $content;
	protected $query;
	
	public function dispatch(){
		ss_error::log($this->name(),'Dispatch '.__CLASS__);
		//ss_error::log($this->name(),'Name');
		//ss_error::log($this->next(),'Next');
		/*if(is_numeric($this->next())){
			return parent::dispatch();
		}*/
		if(is_numeric($this->next())) return $this->wrap($this->forward('ss_api_jsonQuery_detail'));
		//die('Query: '.urldecode($_query));
		return $this->execute();
	}
	
	protected function map($name){
		ss_error::log($name,'Map '.__CLASS__);
		//die(print_r($this->url(),true));
		return 'ss_api_jsonQuery_detail';
		if(!is_numeric($name) & (strlen($name)==2)){
			return 'ss_api_master_version';
		} else {
		}
	}
	
	public function get(){
		ss_error::log('GET '.__CLASS__);
		/*ss_error::log($this->requestUri(),'Request');
		ss_error::log($this->url(),'URL');
		ss_error::log($this->segment(),'Segment');
		ss_error::log($this->subtype(),'Subtype');*/
		$_query=trim(mb_substr($_req=rawurldecode($this->requestUri()),mb_strpos($_req,$_url=$this->url())+mb_strlen($_url)),'/');
		//ss_error::info($_query,'query');
		ss_error::info($this->url(),'URL');
		ss_error::info(rawurldecode($this->requestUri()),'raw URL');
		ss_error::info(rawurldecode($_SERVER['REQUEST_URI']),'raw php URL');
		//$_range=$this->getRange();
		//ss_error::log($_range,'Range');
		//$_table=$this->content=Doctrine::getTable($this->name());
		$this->range=$this->getRange();
		$this->query=Doctrine::getTable($this->name())->detectQuery($_query?$_query:$this->query(),1);
		ss_error::log($this->query,'Query');
		//ss_error::log($this->query->getSqlQuery(),'SQL');
		$this->content=$this->query->getAll(array(),'jsonRef',$this->range);
		//ss_error::log(count($this->content),'Returned rows');
		//$this->content=Doctrine::getTable($this->name())->query($_query?$_query:$this->query(),1,1);
		/*if($_query){
			//$_jsonQuery=new ss_json_query($_query);
			//$_query=$_jsonQuery->getDql();
			//ss_error::info($_query,'ss_json_query to DQL');
			//(($this->content=Doctrine::getTable($this->name())->dqlQuery($_query);
			//$this->content=$_table->fetch($_table->jsonQuery($_table->$_query,false));
			$this->content=$_table->jsonQuery($_table->$_query,false)->getAll();
		} elseif(count($this->query())){
			$this->content=$_table->jsonQuery($_table->$_query,false)->getAll();
		} else {
			//$this->content=$_table->fetch($_table->baseQuery(false));
			$this->content=$_table->baseQuery(false)->getAll();
			//$this->content=Doctrine::getTable($this->name())->dqlQuery();
		}*/
		//ss_error::log(Doctrine::getTable($this->name())->getTemplate('Doctrine_Template_I18n')->getOption('fields'),'Table');
		//$this->data=Doctrine::getTable($this->name())->query($this->query());
		/*foreach($this->data as $obj){
			$this->content[]=$obj->getJSONData();
		}*/
		return parent::get();
	}
	/*
	public function post(){
		ss_error::log('POST '.__CLASS__);
		$className=$this->name();
		$this->data=new $className();
		return parent::post();
	}
	*/
	protected function renderHtml(){
		ss_error::log('Render API HTML '.__CLASS__);
		$table='';
		foreach($this->content as $item){
			$row='<td><a href="'.$this->url($item['id']).'">open-></a><td>';
			foreach($item as $key=>$val){
				if(is_array($val) || is_object($val))$val=print_r($val,true);
				$row.="<td>{$val}</td>";
			}
			$table.='<tr>'.$row."</tr>\n";
		}
		if(is_array($item)) $table='<h1>'.$this->name()." master</h1><table>\n<tr><th></th><th>".implode('</th><th>',array_keys($item))."</th></tr>\n".$table."\n</table>\n";
		return $table;
	}
	
	protected function renderJson(){
		ss_error::log('Render API JSON '.__CLASS__);
		//ss_error::log($this->query->getDqlPart('offset'),'offset');
		$result=new k_JsonResponse($this->content);
		/*if(isset($this->range) || !is_empty($this->query->getDqlPart('limit'))) {
			$result->setHeader('Content-Range','tems '.$this->range[0].'-'.$this->range[1].'/'.$this->query->count());
		}*/
		if(count($_offset=$this->query->getDqlPart('offset'))){
			$_offset=end($_offset);
		} else {
			$_offset='0';
		}
		//ss_error::log($_offset,'offset');
		$result->setHeader('Content-Range','items '.$_offset.'-'.($_offset+count($this->content)-1).'/'.($this->query->getCount()));
		//ss_error::info($this->query->getDqlPart('limit'),'Limit');
		//if(!empty($this->query->getDqlPart('limit'))) $result->setHeader('Location',$this->url($_result['id']));//$total=$this->query->count();
		return $result;
	}
	
	
	protected function postJson(){
		ss_error::log('POST JSON '.__CLASS__);
		//ss_error::log($this->name(),'postJSON handler for '.__CLASS__);
		$_table=Doctrine::getTable($this->name());
		$json=json_decode($this->rawHttpRequestBody(),true);
		$_result=$_table->newJsonData($this->name(),$json);
		if(empty($_result)) return new k_MethodNotAllowed();
		//ss_error::log($_result,'Result');
		$result=new k_JsonResponse($_result);
		$result->setHeader('Location',$this->url($_result['id']));
		$result->setStatus(201);
		return $result;
		//$json=$this->data->sanitize(json_decode($this->rawHttpRequestBody(),true));
		$this->data->fromArray($json,'From Array');
		//$this->data->save();
		$result=new k_JsonResponse($this->data->getJSONData());
		$result->setHeader('Location',$this->url($this->data['id']));
		$result->setStatus(201);
		return new k_JsonResponse($result);
		//ss_error::log($this->data->toArray(),'Result');
	}
}

class ss_api_jsonQuery_detail extends ss_konstrukt_detailComponent{
	protected $mapper;
	protected $data;
	protected $content;
	
	public function get(){
		ss_error::log('GET '.__CLASS__);
		$_table=Doctrine::getTable($this->context->name());
		//die($this->data=Doctrine::getTable($this->context->name())->query($this->name(),$this->query()));
		//$this->data=Doctrine::getTable($this->context->name())->single($this->name());
		//$this->content=$_table->fetchOne($_table->primaryQuery($this->name()));
		$this->content=$_table->primaryQuery($this->name())->getOne();
		//$this->content=$_table=query()
		//$this->content=$this->data[0];
		return parent::get();
	}
	
	protected function renderHtml(){
		ss_error::log('Render API HTML '.__CLASS__);
		$table='';
		foreach($this->content as $key=>$val){
			if(is_array($val) || is_object($val))$val=print_r($val,true);
			$table.="<tr><td>{$key}</td><td>{$val}</td></tr>\n";
		}
		$table='<h1>'.$this->name()." detail</h1><table>\n".$table."\n</table>\n";
		return $table;
	}
	
	protected function renderJson(){
		ss_error::log('Render API JSON '.__CLASS__);
		return new k_JsonResponse($this->content);
	}
	
	public function put(){
		ss_error::log('PUT '.__CLASS__);
		$_table=Doctrine::getTable($this->context->name());
		$this->data=$_table->queryPrimary($this->name(),2,2);
		//$this->data=$_table->primaryQuery($this->name(),2)->getOne(array(),Doctrine::HYDRATE_RECORD);
		//$this->data=Doctrine::getTable($this->context->name())->query(array_merge(array('id'=>$this->name()),$this->query()))->getFirst();
		return parent::put();
	}
	
	protected function putJson(){
		ss_error::log('PUT JSON '.__CLASS__);
		//throw new k_NotAcceptable();
		$_table=Doctrine::getTable($this->context->name());
		$json=json_decode($this->rawHttpRequestBody(),true);
		if(!$_table->setJsonData($this->name(),$json)) return new k_NotAcceptable();
		return new k_JsonResponse(true);
		//$json=$this->data->sanitize($raw=json_decode($this->rawHttpRequestBody(),true));
		//ss_error::log($raw,'Raw');
		//ss_error::log(,'Result');
		//ss_error::log($this->data->toArray(true),'Data');
		//ss_error::log($json,'Request');
		//$this->data->synchronizeWithArray($json,'Sync');
		//ss_error::log($this->data->toArray(),'Result');
		//$this->data->save();
		//return new k_JsonResponse($this->data->getJSONData());
		
	}
}
?>